package org.pay.mch.user.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.pay.mch.common.service.RpcCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.pay.core.common.constant.Constant;
import org.pay.core.common.constant.MchConstant;
import org.pay.core.common.constant.RetEnum;
import org.pay.core.common.domain.BizResponse;
import org.pay.core.common.domain.PayPageRes;
import org.pay.core.common.domain.PayResponse;
import org.pay.core.entity.MchPassage;
import org.pay.core.entity.MchQrCode;
import org.pay.mch.common.ctrl.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author: yangshancheng
 * @date: 17/12/21
 * @description:
 */
@Controller
@RequestMapping(Constant.MCH_CONTROLLER_ROOT_PATH + "/mch_qrcode")
@PreAuthorize("hasRole('"+ MchConstant.MCH_ROLE_NORMAL+"')")
public class MchQrCodeController extends BaseController {

    @Autowired
    private RpcCommonService rpcCommonService;

    @RequestMapping("/add")
    @ResponseBody
    public ResponseEntity<?> add(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String appId = getStringRequired(param, "appId");
        String channels = getStringRequired(param, "channels");
        String codeName = getStringRequired(param, "codeName");
        Long minAmount = param.getLong("minAmount");
        Long maxAmount = param.getLong("maxAmount");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setMchId(getUser().getId());
        mchQrCode.setAppId(appId);
        mchQrCode.setChannels(channels);
        mchQrCode.setCodeName(codeName);
        if(minAmount != null) mchQrCode.setMinAmount(minAmount);
        if(maxAmount != null) mchQrCode.setMaxAmount(maxAmount);
        int count = rpcCommonService.rpcMchQrCodeService.add(mchQrCode);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String appId = getStringRequired(param, "appId");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setMchId(getUser().getId());
        mchQrCode.setAppId(appId);
        int count = rpcCommonService.rpcMchQrCodeService.count(mchQrCode);
        if(count == 0) ResponseEntity.ok(PayPageRes.buildSuccess());
        List<MchQrCode> mchQrCodeList = rpcCommonService.rpcMchQrCodeService.select((getPageIndex(param) -1) * getPageSize(param), getPageSize(param), mchQrCode);
        return ResponseEntity.ok(PayPageRes.buildSuccess(mchQrCodeList, count));
    }

    /**
     * 查询
     * @return
     */
    @RequestMapping("/view_code")
    @ResponseBody
    public ResponseEntity<?> viewCode(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setMchId(getUser().getId());
        mchQrCode.setId(id);
        mchQrCode = rpcCommonService.rpcMchQrCodeService.find(mchQrCode);
        if(mchQrCode == null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_QR_CODE_STOP));
        }
        if(MchConstant.PUB_YES != mchQrCode.getState().byteValue()) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_RECORD_NOT_EXIST));
        }
        StringBuilder sb = new StringBuilder(mainConfig.getMchApiUrl() + "/payment/qrcode?");
        sb.append("mchId=").append(mchQrCode.getMchId()).append("&appId=").append(mchQrCode.getAppId())
                .append("&codeId=").append(mchQrCode.getId());

        // 如果是平台用户,需要得到渠道ID
        if(MchConstant.MCH_TYPE_PLATFORM == getUser().getType()) {
            MchPassage mchPassage = new MchPassage();
            mchPassage.setMchId(getUser().getId());
            List<MchPassage> mchPassageList = rpcCommonService.rpcMchPassageService.selectAll(mchPassage);
            if(CollectionUtils.isEmpty(mchPassageList)) {
                // 商户没有配置扫码支付渠道
                // TODO
            }else {
                sb.append("&passageId=").append(mchPassageList.get(0).getPassageId());
            }

        }

        JSONObject data = new JSONObject();
        data.put("codeUrl", sb.toString());
        // codeUrl = '/api/payment/qrcode_img_get?' + 'url=' + data.payParams.codeUrl + '&widht=200&height=200';
        data.put("codeImgUrl", mainConfig.getMchApiUrl() +  "/payment/qrcode_img_get?url=" + URLEncoder.encode(sb.toString()) + "&widht=200&height=200");
        return ResponseEntity.ok(PayResponse.buildSuccess(data));
    }

    /**
     * 查询
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setMchId(getUser().getId());
        mchQrCode.setId(id);
        mchQrCode = rpcCommonService.rpcMchQrCodeService.find(mchQrCode);
        return ResponseEntity.ok(PayResponse.buildSuccess(mchQrCode));
    }

    @RequestMapping("/update")
    @ResponseBody
    public ResponseEntity<?> update(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        String channels = param.getString("channels");
        String codeName = param.getString("codeName");
        Byte state = param.getByte("state");
        Long minAmount = param.getLong("minAmount");
        Long maxAmount = param.getLong("maxAmount");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setId(id);
        if(StringUtils.isNotBlank(channels)) mchQrCode.setChannels(channels);
        if(StringUtils.isNotBlank(codeName)) mchQrCode.setCodeName(codeName);
        if(state != null) mchQrCode.setState(state);
        if(minAmount != null) mchQrCode.setMinAmount(minAmount);
        if(maxAmount != null) mchQrCode.setMaxAmount(maxAmount);
        int count = rpcCommonService.rpcMchQrCodeService.update(mchQrCode);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

}
